//
//  TRMyhomeViewController.m
//  WeiMiLan
//
//  Created by anan on 14/11/18.
//  Copyright (c) 2014年 Mac. All rights reserved.
//

#import "TRMyhomeViewController.h"
#import "TRUserLoginViewController.h"
#import "TREmptyViewController.h"
#import "TRAboutViewController.h"
#import "TRMyUploadViewController.h"
#import "TRMyCollectViewController.h"
#import "TRFocusViewController.h"

@interface TRMyhomeViewController ()
@property (strong, nonatomic) TREmptyViewController *emptyVC;
@property (weak, nonatomic) IBOutlet UISwitch *isOpenNoti;
- (IBAction)isOpenNotiAction:(UISwitch *)sender;

@end

@implementation TRMyhomeViewController

- (UIViewController *)emptyVC {
    if (_emptyVC == nil) {
        _emptyVC = [[TREmptyViewController alloc]init];
    }
    return _emptyVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
     NSLog(@"TRMyhomeViewController");
    [self initNavigation];
    
    BOOL isOpen =  [NSStandardUserDefaults boolForKey:@"isOpenNoti"];
    
    self.isOpenNoti.on = isOpen;
   
    
    self.imageViewUserHead.layer.masksToBounds = YES;
    self.imageViewUserHead.layer.cornerRadius = 7; //设置图片圆角的尺度
    if ([QLPropertyUtils getBoolByKey:@"guid_edit_userdetail" defaultValue:NO]==NO) {
        self.viewGuide.hidden = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(guideTap:)];
        [self.viewGuide addGestureRecognizer:tap];
    }
}

- (void)guideTap:(id)sender
{
    self.viewGuide.hidden = YES;
    [QLPropertyUtils putBoolByKey:@"guid_edit_userdetail" value:YES];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self updateUserInfo];
    
    NSDictionary *userInfo = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    NSString *user=[userInfo objectForKey:@"ID"];
    [[NSUserDefaults standardUserDefaults]setObject:user forKey:@"userId"];
    [[QLUserManager shareInstance] detailWithUserId:[userInfo ql_intForKey:@"ID"] callback:^(BOOL isCache, id data) {
    [self updateUserInfo];
    }];
}

- (void)updateUserInfo
{
    NSDictionary *userInfo = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    
    if ([[userInfo ql_stringForKey:@"HEAD_PIC_URL"] containsString:@"upload/users"]) {
          [self.imageViewUserHead sd_setImageWithURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:@"urlHeader"]] placeholderImage:[UIImage imageNamed:@"nodata_avator"]];
    } else {
        [self.imageViewUserHead sd_setImageWithURL:[NSURL URLWithString:[userInfo ql_stringForKey:@"HEAD_PIC_URL"]] placeholderImage:[UIImage imageNamed:@"nodata_avator"]];
    }
    
    
    
    //"http://pingpic.vsmu.cn/upload/users"
    
    self.weChatNavigationBar.titleLabel.text=[userInfo ql_stringForKey:@"NAME"];
    
    if ((userInfo.count == 0) || [userInfo[@"UPDATE_COUNT"] isEqualToString:@"(null)"]) {
        self.labelUploadCount.text = @"0";
    } else {
        self.labelUploadCount.text = [NSString stringWithFormat:@"%@",userInfo[@"UPDATE_COUNT"]];
        
    }
    //self.labelFollowCount.text = [NSString stringWithFormat:@"%@",userInfo[@"FOLLOWED_TOTAL"]];
    NSLog(@"------%@",userInfo[@"SIGNATURE"]);
    if ((userInfo.count == 0) || [userInfo[@"SIGNATURE"] isEqualToString:@"(null)"] || ![[userInfo allKeys] containsObject:@"SIGNATURE"]) {
        self.userSignatureLabel.text = @"个性签名";
    } else {
        self.userSignatureLabel.text = [NSString stringWithFormat:@"%@",userInfo[@"SIGNATURE"]];
    }
    
    if ((userInfo.count == 0) || [userInfo[@"NAME"] isEqualToString:@"(null)"] || ![[userInfo allKeys] containsObject:@"NAME"]) {
        self.userNameLabel.text = @"昵称";
    } else {
        self.userNameLabel.text = [NSString stringWithFormat:@"%@",userInfo[@"NAME"]];
    }
    
    if ((userInfo.count == 0) || [userInfo[@"FOLLOWED_TOTAL"] isEqualToString:@"(null)"]) {
        self.labelFollowCount.text = @"0";
    } else {
        self.labelFollowCount.text = [NSString stringWithFormat:@"%@",userInfo[@"FOLLOWED_TOTAL"]];
    }
    
    if ((userInfo.count == 0) || [userInfo[@"FANS_TOTAL"] isEqualToString:@"(null)"]) {
        self.labelFansCount.text = @"0";
    } else {
        self.labelFansCount.text = [NSString stringWithFormat:@"%@",userInfo[@"FANS_TOTAL"]];

    }
    if ((userInfo.count == 0) || [userInfo[@"SHARED_TOTAL"] isEqualToString:@"(null)"]) {
        self.labelUpCount.text = @"0";
    } else {
     self.labelUpCount.text = [NSString stringWithFormat:@"%@",userInfo[@"SHARED_TOTAL"]];
        
    }
    
}

- (void)initNavigation
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.weChatNavigationBar=[[WeChatNavigationBar alloc] init];
    [self.view insertSubview:self.weChatNavigationBar belowSubview:self.viewGuide];
    NSDictionary *userInfo = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    NSString *nickname = [userInfo ql_stringForKey:@"NAME"];
    nickname = nickname==nil?[QLPropertyUtils getStringByKey:@"account" defaultValue:nil]:nickname;
    
    self.weChatNavigationBar.titleLabel.text=nickname;
//    [self.weChatNavigationBar.leftButton addTarget:self action:@selector(shouLeftVC) forControlEvents:UIControlEventTouchUpInside];
    self.weChatNavigationBar.leftButton.hidden = NO;
    self.weChatNavigationBar.leftButton.center = CGPointMake(15 + 11,(self.weChatNavigationBar.height - 20));
    self.weChatNavigationBar.leftButton.width = 22;
    self.weChatNavigationBar.leftButton.height = 22;
    [self.weChatNavigationBar.leftButton setBackgroundImage:[UIImage imageNamed:@"Preferences22"] forState:UIControlStateNormal];
  //  [self.weChatNavigationBar.leftButton setImage:nil forState:UIControlStateNormal];
  //  [self.weChatNavigationBar.leftButton setTitle:@"编辑" forState:UIControlStateNormal];
    [self.weChatNavigationBar.leftButton addTarget:self action:@selector(buttonUserDetailAction:) forControlEvents:UIControlEventTouchUpInside];
  //  [self.weChatNavigationBar.leftButton sizeToFit];
    
    
    self.weChatNavigationBar.rightButton.hidden = NO;
    [self.weChatNavigationBar.rightButton setBackgroundImage:[UIImage imageNamed:@"Close22"] forState:UIControlStateNormal];
    [self.weChatNavigationBar.rightButton setImage:nil forState:UIControlStateNormal];
   // [self.weChatNavigationBar.rightButton setTitle:@"退出" forState:UIControlStateNormal];
    self.weChatNavigationBar.rightButton.center = CGPointMake((self.weChatNavigationBar.width - 10) - 11,(self.weChatNavigationBar.height - 20));
    self.weChatNavigationBar.rightButton.width = 22;
    self.weChatNavigationBar.rightButton.height = 22;
    [self.weChatNavigationBar.rightButton addTarget:self action:@selector(quitLogin) forControlEvents:UIControlEventTouchUpInside];
  //  [self.weChatNavigationBar.rightButton sizeToFit];
}
- (void)quitLogin {
   
    NSDictionary *userInfo = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    NSString *account = [QLPropertyUtils getStringByKey:@"account" defaultValue:nil];
    NSString *key = [NSString stringWithFormat:@"userHeader_%@",account];
    [QLPropertyUtils putStringByKey:key value:userInfo[@"HEAD_PIC_URL"]];
    
    [[QLUserManager shareInstance] userLogout];
    TRUserLoginViewController *vc = [[TRUserLoginViewController alloc] init];
    [self presentViewController:vc animated:YES completion:^{
        
     //   [self deleteFile];
        
    }];
   
}

// 删除沙盒里的文件
-(void)deleteFile {
    // 1.获得沙盒根路径
    NSString *home = NSHomeDirectory();
    
    // 2.document路径
    NSString *docPath = [home stringByAppendingPathComponent:@"Documents"];
    
    NSString *filepath = [docPath stringByAppendingPathComponent:@"data.plist"];
    
    NSFileManager* fileManager=[NSFileManager defaultManager];
    
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:filepath];
    if (!blHave) {
        NSLog(@"no  have");
        return ;
    }else {
        NSLog(@" have");
        BOOL blDele= [fileManager removeItemAtPath:filepath error:nil];
        if (blDele) {
            NSLog(@"dele success");
        }else {
            NSLog(@"dele fail");
        }
        
  }
}
-(void)shouLeftVC
{
    [ApplicationDelegate.ddVC showLeftController:YES];
}

-(void)search:(id)btn{
    UIViewController * vc = [[TRSearchProductViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)removeTopButton{
    
}

-(void)visibleTop{
    
}

#pragma mark - QLMaskNodataViewOnClickDelegate
-(void)onClick:(id)sender
{
    [QLMaskUtil hideNodataMaskWithView:self.view];
}

- (IBAction)buttonWodeshangchuanAction:(id)sender
{
    TRMyCollectViewController *vc = [[QLPlayerManager getStoryboard] instantiateViewControllerWithIdentifier:@"TRMyCollectViewController"];
    vc.goodsStype=TRMySend;

//    TRMyUploadViewController *vc = [[TRMyUploadViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)buttonWodeguanzhuAction:(id)sender
{
    TRMyCollectViewController *vc = [[QLPlayerManager getStoryboard] instantiateViewControllerWithIdentifier:@"TRMyCollectViewController"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)buttonPinpaiAction:(id)sender
{
//    IIIViewController *vc = [[QLPlayerManager getStoryboard] instantiateViewControllerWithIdentifier:@"IIIViewController"];
//    [self.navigationController pushViewController:vc animated:YES];
    TRTabBarViewController * tabVc =ApplicationDelegate.rootVC;
    IIIViewController *vc = [[QLPlayerManager getStoryboard] instantiateViewControllerWithIdentifier:@"IIIViewController"];
    [(UINavigationController*)tabVc.selectedViewController pushViewController:vc animated:YES];
    [ApplicationDelegate.ddVC showRootController:YES];
}

- (IBAction)buttonPaihangbangAction:(id)sender
{
//    TRListTableViewController *vc = [[QLPlayerManager getStoryboard] instantiateViewControllerWithIdentifier:@"TRListTableViewController"];
//    vc.usage = sharedVC;
//    [self.navigationController pushViewController:vc animated:YES];
  //  self.emptyVC.navTitle = @"要闻推送";
  //  [self presentViewController:self.emptyVC animated:YES completion:nil];
}

- (IBAction)buttonLogsAction:(id)sender
{
    TRLogsViewController *vc = [[TRLogsViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)buttonYaoqingAction:(id)sender
{
    [self initShareView];
}

- (IBAction)buttonShezhiAction:(id)sender
{
    TRSystemSettingViewController *vc = [[TRSystemSettingViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark--分享视图
-(void)initShareView
{
    NSArray*shareButtonTitleArray = @[@"微信",@"微信朋友圈",@"QQ",@"新浪微博",@"QQ空间",@"复制"];
    NSArray * shareButtonImageNameArray= @[@"sns_icon_22",@"sns_icon_23",@"sns_icon_40",@"sns_icon_1",@"QQkj",@"fuzhi"];
    self.lxActivity = [[LXActivity alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" ShareButtonTitles:shareButtonTitleArray withShareButtonImagesName:shareButtonImageNameArray];
    [self.lxActivity showInView:ApplicationDelegate.window];
}

#pragma mark --LXActivityDelegate
- (void)didClickOnImageIndex:(NSInteger )imageIndex
{
    switch (imageIndex) {
        case 0:
            [self sendAppLinkContent:WXSceneSession];
            break;
        case 1:
            [self sendAppLinkContent:WXSceneTimeline];
            break;
        case 2: //QQ分享
            
            [UMSocialQQHandler setQQWithAppId:QQWithAppId appKey:QQWithAppKey url:down_URL];
            
            [self yixunshare:UMShareToQQ];
            
            break;
        case 3: //新浪微博
            
            
            [self yixunshare:UMShareToSina];
            break;
        case 4://QQ空间
            
            [UMSocialQQHandler setQQWithAppId:QQWithAppId appKey:QQWithAppKey url:down_URL];
            
            
            [self yixunshare:UMShareToQzone];
            break;
        case 5:
        {
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            pasteboard.string =[NSString stringWithFormat:@"%@\n%@",share_AppContent,down_URL];
            [SVProgressHUD showErrorWithStatus:@"app网址已经复制，您可以直接发送给好友"];
        }
            break;
//        case 6:
//            //设置易信Appkey和分享url地址
//            [UMSocialYixinHandler setYixinAppKey:YiXunWithAppId url:down_URL];
//            
//            [self yixunshare:UMShareToYXSession];
//            
//            
//            break;
//        case 7:
//            //设置易信Appkey和分享url地址
//            [UMSocialYixinHandler setYixinAppKey:YiXunWithAppId url:down_URL];
//            
//            [self yixunshare:UMShareToYXTimeline];
//            break;
            
        default:
            break;
    }
}

- (void) sendAppLinkContent:(int)scene
{
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = share_AppTitle;
    message.description = share_AppContent;
    [message setThumbImage:shre_AppImage];
    
    WXWebpageObject *ext = [WXWebpageObject object];
    ext.webpageUrl = share_AppURL;
    
    message.mediaObject = ext;
    
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = scene;
    
    [WXApi sendReq:req];
}

-(void)yixunshare:(NSString *)pingtai
{
    NSString *shareText = share_AppContent;
    UIImage *shareImage = shre_AppImage;
    if ([pingtai isEqualToString:UMShareToSina]) {
        shareText = [NSString stringWithFormat:@"%@%@",@"我在#微私募#轻松看新闻 - 微私募天天有股票新闻 >>",down_URL];
        shareImage=ApplicationDelegate.shareImageHD;
    }
    UMSocialUrlResource *UMUrl=[[UMSocialUrlResource alloc] initWithSnsResourceType:UMSocialUrlResourceTypeDefault url:down_URL];
    
    [[UMSocialDataService defaultDataService] postSNSWithTypes:@[pingtai] content:shareText image:shareImage location:nil urlResource:UMUrl presentedController:self completion:^(UMSocialResponseEntity * response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"成功" message:@"分享成功" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil];
            [alertView show];
        } else if(response.responseCode != UMSResponseCodeCancel) {
            UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"失败" message:@"分享失败" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil];
            [alertView show];
        }
    }];
}

- (IBAction)buttonUserDetailAction:(id)sender
{
    TRUserDetailViewController *vc = [[TRUserDetailViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)buttonFocusAction:(id)sender {
//    TRFocusViewController *vc = [[TRFocusViewController alloc] init];
//    [self.navigationController pushViewController:vc animated:YES];
    TRFocusViewController *vc = [TRFocusViewController new];
    NSDictionary *userInfo = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    if (userInfo) {
        vc.userId = userInfo[@"ID"];
        [self presentViewController:vc animated:YES completion:nil];
    }
}
- (IBAction)buttonUploadAction:(id)sender {
//    TRMyUploadViewController *vc = [[TRMyUploadViewController alloc] init];
//    [self.navigationController pushViewController:vc animated:YES];
    TRMyCollectViewController *vc = [[TRMyCollectViewController alloc] init];
    vc.goodsStype=TRMySend;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)buttonFansAction:(id)sender
{
    TRFansViewController *vc = [TRFansViewController new];
    NSDictionary *userInfo = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    if (userInfo) {
        vc.userId = userInfo[@"ID"];
        [self presentViewController:vc animated:YES completion:nil];
    }
}

- (IBAction)buttonMyOrderAction:(id)sender {
    TRMyOrderViewController *vc = [[TRMyOrderViewController alloc] init];
    [self presentViewController:vc animated:YES completion:nil];
}

- (IBAction)buttonMyCarAciton:(id)sender {
//    TRBuyCarViewController *vc = [[TRBuyCarViewController alloc] init];
//    [self presentViewController:vc animated:YES completion:nil];
    self.emptyVC.navTitle = @"打赏";
    [self presentViewController:self.emptyVC animated:YES completion:nil];
}

- (IBAction)buttonAddressAction:(id)sender {
    
    TRAboutViewController *vc = [[TRAboutViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
   // [self.navigationController pushViewController:about animated:YES];
//    TRAddressListViewController *vc = [[TRAddressListViewController alloc] init];
//    [self presentViewController:vc animated:YES completion:nil];
//    self.emptyVC.navTitle = @"关于我们";
  //  [self presentViewController:self.emptyVC animated:YES completion:nil];
}

- (IBAction)isOpenNotiAction:(UISwitch *)sender {
    
    [self.isOpenNoti setOn:!self.isOpenNoti.isOn animated:YES];
    
    [NSStandardUserDefaults setBool:self.isOpenNoti.isOn forKey:@"isOpenNoti"];
    
}
@end
